package com.leyou.lock;

import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 *
 */
public class RedisLockImpl2 implements RedisLock{
    private StringRedisTemplate redisTemplate;

    private String key;

    public RedisLockImpl2(StringRedisTemplate redisTemplate, String key){
        this.key = key;
        this.redisTemplate =redisTemplate;
    }

    @Override
    public boolean lock(long locktime) {
        // 获取线程信息作为值，方便判断是否是自己的锁
        String value = Thread.currentThread().getId()+"";
        // 尝试获取锁
        Boolean boo = redisTemplate.opsForValue().setIfAbsent(key, value, locktime, TimeUnit.SECONDS);
        // 判断结果
        return boo != null && boo;
    }

    @Override
    public void unlock() {
        // 获取线程信息作为值，方便判断是否是自己的锁
        String value = Thread.currentThread().getId()+"";
        // 获取现在的锁的值
        String val = redisTemplate.opsForValue().get(key);
        // 判断是否是自己
        if(value.equals(val)) {
            // 删除key即可释放锁
            redisTemplate.delete(key);
        }
    }
}
